package com.hangzhou.xyj.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.SimpleUserDao;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.GroupModel;
import com.hangzhou.xyj.model.SimpleUserModel;
import com.hangzhou.xyj.model.XXLocation;
import com.hangzhou.xyj.net.handler.AddDynamicHandler;
import com.hangzhou.xyj.net.handler.GetGroupsInfoHandler;
import com.hangzhou.xyj.net.handler.QuitGroupHandler;
import com.hangzhou.xyj.net.handler.ReportHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.request.AddDynamicReq;
import com.hangzhou.xyj.net.request.GetGroupsInfoReq;
import com.hangzhou.xyj.net.request.QuitGroupReq;
import com.hangzhou.xyj.net.request.ReportReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.dialog.TipsDialog;
import com.hangzhou.xyj.ui.fragment.MyEaseChatFragment;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.SelectMenuDialog;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.DataKey;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by neo.duan on 2016/1/19.
 * 聊天页面
 */
public class ChatActivity extends BaseActivity {
    private static final String TAG = "ChatActivity";

    private String mUserIdOrGroupId;
    private int mChatType;

    private MyEaseChatFragment mChatFragment;
    private GroupModel mGroupInfo;//圈子基本信息

    @Override
    public void initTop() {
        enableTop(true);
        enableTitle(true, "聊天页面");
        enableRightNav(true, R.drawable.ic_action_menu);
        setOnNavRightListener(new CommonTitleBarView.OnNavRightListener() {
            @Override
            public void onNavRight() {
                switch (mChatType) {
                    case EaseConstant.CHATTYPE_SINGLE://单聊
                        showSingChatMenuDialog();
                        break;
                    case EaseConstant.CHATTYPE_GROUP://群聊
                        showGroupChatMenuDialog();
                        break;
                    default:
                        showSingChatMenuDialog();
                        break;
                }
            }
        });
    }

    @Override
    public void initIntentData(Intent intent) {
        super.initIntentData(intent);
        if (intent != null) {
            mUserIdOrGroupId = intent.getStringExtra(DataKey.USER_ID);//圈子的环信Id 或者 用户的ID
            mChatType = intent.getIntExtra(DataKey.CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        }
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_chat);
    }

    @Override
    public void initViews() {
        //new出EaseChatFragment或其子类的实例
        mChatFragment = new MyEaseChatFragment();
        //传入参数
        Bundle args = new Bundle();
        args.putInt(EaseConstant.EXTRA_CHAT_TYPE, mChatType);
        args.putString(EaseConstant.EXTRA_USER_ID, mUserIdOrGroupId);
//        args.putString(EaseConstant.EXTRA_TO_USERNICK,mUserName);
        mChatFragment.setArguments(args);
        getSupportFragmentManager().beginTransaction().add(R.id.chat_root_layout, mChatFragment).commit();
    }

    @Override
    public void initDatas() {
        switch (mChatType) {
            case EaseConstant.CHATTYPE_SINGLE:
                SimpleUserDao hxDao = new SimpleUserDao(mContext);
                SimpleUserModel hxUser = hxDao.getUser(mUserIdOrGroupId);
                if (hxUser != null) {
                    enableTitle(true, hxUser.getNickName());
                }
                break;
            case EaseConstant.CHATTYPE_GROUP://群聊
                getGroupInfo(mUserIdOrGroupId);
                break;
        }
    }

    @Override
    public void initListeners() {

    }

    /**
     * 弹出单聊菜单
     */
    private void showSingChatMenuDialog() {
        SelectMenuDialog dialog = new SelectMenuDialog(mContext);
        dialog.setMenu(new String[]{
                "清空聊天记录"
        }, new SelectMenuDialog.SelectMenuClickListener() {
            //按钮添加点击事件
            @Override
            public void onSelectMenuClick(Dialog dialog, View item, int position) {
                switch (position) {
                    case 0:
                        mChatFragment.emptyHistory();
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 弹出群聊菜单
     */
    private void showGroupChatMenuDialog() {

        new AsyncTask<Void, Void, EMGroup>() {

            @Override
            protected EMGroup doInBackground(Void... params) {
                try {
                    return EMClient.getInstance().groupManager().getGroupFromServer(mUserIdOrGroupId);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(EMGroup emGroup) {
                super.onPostExecute(emGroup);
                if (emGroup == null) {
                    showGroupChatNormalMenu();
                } else {
                    String owner = emGroup.getOwner();
                    if (owner.equals(XYJApplication.getUserInfo().getUserId())) {
                        showGroupChatOwnerMenu();
                    } else {
                        showGroupChatNormalMenu();
                    }
                }

            }
        }.execute();
    }

    private void showGroupChatOwnerMenu() {
        SelectMenuDialog dialog = new SelectMenuDialog(mContext);
        dialog.setMenu(new String[]{
                "群资料", "分享", "举报"
        }, new SelectMenuDialog.SelectMenuClickListener() {
            //按钮添加点击事件
            @Override
            public void onSelectMenuClick(Dialog dialog, View item, int position) {
                switch (position) {
                    case 0:
                        IntentManager.getInstance().goGroupInfoActivity(ChatActivity.this, mUserIdOrGroupId);
                        break;
                    case 1:
                        TipsDialog tipsDialog = new TipsDialog(mContext, "提示", "确定分享该圈子到动态？", "确定", "取消") {
                            @Override
                            protected void OnClickNegativeButton() {
                                this.dismiss();
                            }

                            @Override
                            protected boolean OnClickPositiveButton() {
                                shareGroup();
                                return true;
                            }
                        };
                        tipsDialog.show();
                        break;
                    case 2:
                        report(Integer.valueOf(mGroupInfo.getId()));
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 普通成员进入群聊，用户展示的菜单
     */
    private void showGroupChatNormalMenu() {
        SelectMenuDialog dialog = new SelectMenuDialog(mContext);
        dialog.setMenu(new String[]{
                "群资料", "退出该群", "分享", "举报"
        }, new SelectMenuDialog.SelectMenuClickListener() {
            //按钮添加点击事件
            @Override
            public void onSelectMenuClick(Dialog dialog, View item, int position) {
                switch (position) {
                    case 0:
                        IntentManager.getInstance().goGroupInfoActivity(ChatActivity.this, mUserIdOrGroupId);
                        break;
                    case 1: //退群
                        String userId = XYJApplication.getUserInfo().getUserId();
                        QuitGroupReq req = new QuitGroupReq(Integer.valueOf(userId), mGroupInfo.getId());
                        HttpLoader.getInstance().sendRequest(new QuitGroupHandler(req, new MyHttpResponseListener() {
                            @Override
                            public void onSuccess(Object model) {
                                super.onSuccess(model);
                                ToastUtil.show("退出群成功");
                                finish();
                            }
                        }, 0));
                        break;
                    case 2:
                        TipsDialog tipsDialog = new TipsDialog(mContext, "提示", "确定分享该圈子到动态？", "确定", "取消") {
                            @Override
                            protected void OnClickNegativeButton() {
                                this.dismiss();
                            }

                            @Override
                            protected boolean OnClickPositiveButton() {
                                shareGroup();
                                return true;
                            }
                        };
                        tipsDialog.show();
                        break;
                    case 3:
                        report(Integer.valueOf(mGroupInfo.getId()));
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    /**
     * 获取群的基本信息
     *
     * @param EMGroupId 环信群ID
     * @return
     * @author yaohuix
     * @date 2016/5/10 14:30
     */
    private void getGroupInfo(String EMGroupId) {
        GetGroupsInfoReq getGroupsInfoReq = new GetGroupsInfoReq(EMGroupId);
        HttpLoader.getInstance().sendRequest(new GetGroupsInfoHandler(getGroupsInfoReq, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                mGroupInfo = ((List<GroupModel>) model).get(0);
                enableTitle(true, mGroupInfo.getGroupName());
            }
        }, 0));
    }

    /**
     * 举报
     *
     * @param reportId 圈子的ID（不是环信的群ID）
     * @return
     * @author yaohuix
     * @date 2016/5/10 14:34
     */
    private void report(int reportId) {
        ReportReq reportReq = new ReportReq(reportId, 2, mMyUserId);
        HttpLoader.getInstance().sendRequest(new ReportHandler(reportReq, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                ToastUtil.show("举报成功");
            }
        }, 0));
    }


    /**
     * @param
     * @return
     * @author yaohuix
     * @date 2016/5/10 14:53
     */
    public void shareGroup() {
        String textContent;//文本信息
        List<String> pathList = new ArrayList<>();
        String address;
        String location;
        //获取详细地址和城市
        XXLocation xxLocation = XYJApplication.getInstance().getLocation();
        if (xxLocation != null) {
            if (StringUtil.isNotEmpty(xxLocation.getAddress())) {
                address = xxLocation.getAddress();
            } else {
                address = "";
            }
            if (StringUtil.isNotEmpty(xxLocation.getCity())) {
                location = xxLocation.getCity();
            } else {
                location = XYJApplication.getUserInfo().getZone();
            }
        } else {
            address = "";
            location = XYJApplication.getUserInfo().getZone();
        }

        textContent = "欢迎您加入圈子：【" + mGroupInfo.getGroupName() + "】，ID：&$$&" + mGroupInfo.getId() + "$&&$";
        pathList.add(mGroupInfo.getGroupImage());
        AddDynamicReq addDynamicReq = new AddDynamicReq(2, XYJApplication.getUserInfo().getUserId(),
                textContent, address, location, pathList);
        HttpLoader.getInstance().sendRequest(new AddDynamicHandler(addDynamicReq, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                hideLoadingDialog();
                TipsDialog dialog = new TipsDialog(mContext, "分享成功！", "可以到我的动态页面查看", "现在查看", "以后再说") {
                    @Override
                    protected void OnClickNegativeButton() {
                        this.dismiss();
                    }

                    @Override
                    protected boolean OnClickPositiveButton() {
                        //跳转到我的动态
                        IntentManager.getInstance().goActivity(mContext, new Intent(mContext, MyActiveInfoActivity.class));
                        closeActivity();
                        return true;
                    }

                };
                dialog.show();
            }
        }, 0));
    }

}
